L.RoomList = L.Class.extend({
	includes : L.Mixin.Events,

	initialize : function(roomListType, couplingOptions) {
		this._roomListType = roomListType;
		this._rooms = [];
		this._group = null;

		this._couplingOptions = couplingOptions;
		if ( this._couplingOptions != null && this._couplingOptions.enabled )
			this._couple(this._couplingOptions);
	},

	addRoom : function(roomId, ownerId, options) {
		
		var background = null;
		if ( options && options.uploadedFileId && options.uploadedFileName ) {
			background = { 	
				uploadedFileId: options.uploadedFileId,
				uploadedFileName: options.uploadedFileName
			};
		}
		
		var room = new L.Room( 
			roomId, 
			this._roomListType,
			ownerId,
			background,
			this._couplingOptions);
		
//		console.log("room.setRoomList(this);");
		room.setRoomList(this);
		
		this._rooms.unshift({
			roomId : roomId,
			room : room
		});

		this.fire('roomAction', {
			action_name : 'addRoom',
			attr_list : {
				roomId : roomId,
				room : room,
				type : this._roomListType,
				options: options
			}
		});
	},
	
	removeRoom : function(roomId) {
		if (this._findIndex(roomId) == -1) {
			console.log("[WARNING] L.Model.removeRoom intento eliminar un objeto inexistente en este roomList");
			return;
		}
		var index = this._findIndex(roomId);
		var room = this._rooms[index].room;
		this._rooms.splice(index, 1);

		this.fire('roomAction', {
			action_name : 'removeRoom',
			attr_list : {
				roomId : roomId,
				type : this._roomListType
			}
		});
	},

	moveRoom : function(roomId, old_index, new_index) {
		var rooms = this._rooms;

		var index = this._findIndex(roomId);
		var room_container_aux = this._rooms[index];

		rooms.splice(old_index, 1);
		rooms.splice(new_index, 0, room_container_aux);

		this.fire('roomAction', {
			action_name : 'moveRoom',
			attr_list : {
				roomId : roomId,
				old_index : old_index,
				new_index : new_index,
				type : this._roomListType
			}
		});
	},

	eachRoom : function(fn, context) {
		var rooms = this._rooms;
		for ( var i = 0, n = rooms.length; i < n; i++) {
			fn.call(context, rooms[i].room);
		}
	},

	containsRoomId : function(roomId) {
		return this._findIndex(roomId) != -1;
	},

	getRoom : function(roomId) {
		var index = this._findIndex(roomId);
		return this._rooms[index].room;
	},
	
	getRooms: function() {
		return this._rooms;
	},

	_findIndex : function(roomId) {
		var rooms = this._rooms;
		for ( var i = 0, n = rooms.length; i < n; i++) {
			if (rooms[i].roomId == roomId) {
				return i;
			}
		}
		return -1;
	},
	
	setGroup: function(group) {
		this._group = group;
	},
	
	getGroup: function() {
		return this._group;
	},
	
	_couple: function(couplingOptions) {
		couplingOptions.adapter.coupleObject(
			couplingOptions.carriedId, 
			this,
			{
				messageType: "EVENT",
				explicitMapping: ["addRoom", "removeRoom", "moveRoom"]
			}
		);
	}

});
